#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>

#define SIZE 1024
#define ARGC_MAX 64
#define NONEREDIR -1
#define STDINREDIR 0
#define STDOUTREDIR 1
#define APPENDREDIR 2
#define FIND_FILE(buf, pos) do{ while(isspace(buf[pos])) ++pos; }while(0)

char* argv[ARGC_MAX];
char oldpwd[SIZE];
char pwd[SIZE];
int lastcode = 0;
int redir_type = NONEREDIR;
char* filename = NULL;

const char* User(){
    char* user = getenv("USER");
    if(user)
        return user;
    return "None";
}
const char* HostName(){
    char* hostname = getenv("HOSTNAME");
    if(hostname)
        return hostname;
    return "None";
}
const char* Pwd(){
    char* pwd = getenv("PWD");
    if(pwd)
        return pwd;
    return "None";
}

void checkredir(char* in)
{
    redir_type = NONEREDIR;//每次读取命令行后必须重置，否则下次的值不变会影响正常IO
    filename = NULL;
    int pos = strlen(in)-1;
    while(pos >= 0)
    {
        if(in[pos] == '>')
        {
            redir_type = STDOUTREDIR;
            in[pos] = '\0';
            if(in[pos-1] == '>')
            {
                redir_type = APPENDREDIR;
                in[pos-1] = '\0';
            }
            ++pos;
            FIND_FILE(in, pos);
            filename = in+pos;
            break;
        }
        else if(in[pos] == '<')
        {
            redir_type = STDINREDIR;
            in[pos] = '\0';
            ++pos;
            FIND_FILE(in, pos);
            filename = in+pos;
            break;
        }
        --pos;
    }
}

void remove_space(char* cmd)
{
    int i = strlen(cmd)-1;
    while(i >= 0)
    {
        if(isspace(cmd[i]))
            cmd[i] = '\0';
        else 
        {
            break;
        }
        i--;
    }
}
int Interactive(char* cmd)
{
    printf("[%s@%s %s]$ ", User(), HostName(), Pwd()); 
    fgets(cmd, SIZE, stdin);
    cmd[strlen(cmd)-1] = 0;
    remove_space(cmd);
    checkredir(cmd);
    return strlen(cmd);
}

void Split(char* cmd)
{
    int i=0;
    for(argv[i]=strtok(cmd, " "); argv[++i]=strtok(NULL, " "););
    if(strcmp(argv[0], "ls") == 0)
    {
        argv[i] = (char*)"--color";
        argv[++i] = NULL;
    }
}

int BuildInCmd()
{
    int ret = -1;
    if(strcmp(argv[0], "cd") == 0)
    {
        ret = 1;
        char* target = argv[1];
        if(!target || strcmp(target, "~")==0) target = getenv("HOME"); 
        else if(strcmp(target, "-")==0) 
        {
            target = getenv("OLDPWD");
            if(target == NULL) 
            {
                printf("cd: OLDPWD not set\n");
                return ret;
            }
        };
        char temp[SIZE];
        //修改前先记录当前工作目录
        getcwd(temp, SIZE);
        int r = chdir(target); //修改当前工作目录
        if(r == -1)
        {
            perror("cd");
            return ret;
        }
        //成功修改后将原来的工作目录记录在oldpwd中，并导入环境变量表
        snprintf(oldpwd, SIZE, "OLDPWD=%s", temp);
        putenv(oldpwd);

        getcwd(temp, SIZE); //获取当前工作目录的绝对路径
        snprintf(pwd, SIZE, "PWD=%s", temp); //将更新后的PWD保存在全局的字符数组中
        putenv(pwd); //将PWD的地址导入环境变量表
    }

    else if(strcmp(argv[0], "export") == 0 && argv[1])
    {
        ret = 1;
        char* env = (char*)malloc(strlen(argv[1]+1));
        strcpy(env, argv[1]);
        putenv(env);
    }
    else if(strcmp(argv[0], "echo") == 0)
    {
        ret = 1;
        if(!argv[1])
            printf("\n");
        else
        {
            if(argv[1][0] == '$')
            {
                if(argv[1][1] == '?')
                {
                    printf("%d\n", lastcode);
                    lastcode = 0;
                }
                else
                {
                    char* e = getenv(argv[1]+1);
                    if(e)
                        printf("%s\n", e);
                }
            }
            else
            {
                printf("%s\n", argv[1]);
            }
        }
    }
    return ret;
}

void Execute()
{
    pid_t id = fork();
    if(id == 0)
    {
        if(redir_type == STDINREDIR)
        {
            int fd = open(filename, O_RDONLY);
            if(fd < 0)
            {
                perror("open");
                return;
            }
            dup2(fd, 0);
        }
        else if(redir_type == STDOUTREDIR)
        {
            int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
            if(fd < 0)
            {
                perror("open");
                return;
            }
            dup2(fd, 1);
        }
        else if(redir_type == APPENDREDIR)
        {
            int fd = open(filename, O_WRONLY | O_CREAT | O_APPEND, 0666);
            if(fd < 0)
            {
                perror("open");
                return;
            }
            dup2(fd, 1);
        }
        if(argv[0]) //为了命令行第一个字符为重定向设的特例
            execvp(argv[0], argv);
        exit(1);
    }
    else 
    {
        int status;
        pid_t rid = waitpid(id, &status, 0);
        if(rid == id && WIFEXITED(status))
            lastcode = WEXITSTATUS(status);
    }
}
int main()
{
    char commandline[SIZE];
    while(1)
    {
        int n = Interactive(commandline); //打印命令行提示符和获取命令
        if(filename && n == 0) { argv[0] = NULL; goto tar; }//为了命令行第一个字符为重定向设的特例
        if(n == 0) continue; //处理读到空串
        Split(commandline); //字符串分割
        n = BuildInCmd();
        if(n == 1) continue; //判断是否是内建命令
    tar:
        Execute(); //创建子进程执行普通指令
    }
    return 0;
}
